﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace Kokomo
{
	public class RoutedEventBinding : EventBinding
	{
		public RoutedEventBinding()
		{
			this.HandlerDelegate = this.Handle;
		}

		public override void Attach(DependencyObject target)
		{
			UIElement element = target as UIElement;
			if (
				(this.RoutedEvent != null)
				&& (element != null)
				)
			{
				element.RemoveHandler(this.RoutedEvent, this.HandlerDelegate);
			}
		}
		public override void Detach(DependencyObject target)
		{
			UIElement element = target as UIElement;
			if (
				(this.RoutedEvent != null)
				&& (element != null)
				)
			{
				element.AddHandler(this.RoutedEvent, this.HandlerDelegate);
			}
		}

		public RoutedEvent RoutedEvent { get; set; }
		//public RoutedEvent RoutedEvent
		//{
		//    get { return (RoutedEvent)GetValue(RoutedEventProperty); }
		//    set { SetValue(RoutedEventProperty, value); }
		//}

		//// Using a DependencyProperty as the backing store for RoutedEvent.  This enables animation, styling, binding, etc...
		//public static readonly DependencyProperty RoutedEventProperty =
		//    DependencyProperty.Register("RoutedEvent", typeof(RoutedEvent), typeof(RoutedEventBinding), new UIPropertyMetadata(null));

		public RoutedEventHandler HandlerDelegate { get; private set; }
		private void Handle(object target, RoutedEventArgs e)
		{
			ICommand command = this.Command as ICommand;
			if (command != null)
			{
				if (command.CanExecute(this.CommandParameter))
				{
					command.Execute(this.CommandParameter);
				}
			}
		}

		protected override Freezable CreateInstanceCore()
		{
			return new RoutedEventBinding();
		}
	}
}
